package com.coolingme.Constructor;

import com.coolingme.domain.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Constructor中的方法
 *
 * @author wangyue
 * @date 2019/3/16 15:42
 */
public class PersonConstructorTest {
    public static void main(String[] args) {

        try {
            // 创建clazz
            Class clazz = Person.class;

            // 1.获取Constructor无参对象
            Constructor con = clazz.getConstructor();
            // 创建对象 Object o = Constructor对象.newInstance(执行构造方法的所有参数)
            Person person = (Person) con.newInstance();

            // 2.获取Constructor有参对象
            Constructor con1 = clazz.getConstructor(String.class);
            Person person1 = (Person) con1.newInstance("Dylan");

            // 3.获取Constructor 私有 有参对象
            Constructor con2 = clazz.getDeclaredConstructor(String.class, Integer.class);
            // 调用私有构造对象 需要强吻，设置使用权限
            con2.setAccessible(true);
            Person person2 = (Person) con2.newInstance("Dylan", 23);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
